package xyz.weizhi.tanhua.appserver.service;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xyz.weizhi.tanhua.appserver.Exception.BusinessException;
import xyz.weizhi.tanhua.autoconfig.Tempalte.FacebodyTemplate;
import xyz.weizhi.tanhua.autoconfig.Tempalte.OssTemplate;
import xyz.weizhi.tanhua.dubbo.api.UserInfoApi;
import xyz.weizhi.tanhua.model.domain.UserInfo;
import xyz.weizhi.tanhua.model.vo.ErrorResult;
import xyz.weizhi.tanhua.model.vo.UserInfoVo;

import java.io.IOException;

/**
 * @Author milian
 * @Date 2021/10/22 0022 19:56
 */
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FacebodyTemplate facebodyTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void uploadHead(MultipartFile headPhoto, Long id) throws Exception {
        // 上传头像
        String avatar = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        // 进行人脸识别
        boolean hasFaceResult = facebodyTemplate.hasFace(avatar);

        if (!hasFaceResult){
            // 人脸识别失败删除删除照片，返回异常
            ossTemplate.deleteFile(avatar);
            throw new BusinessException(ErrorResult.faceError());
        }
        // 通过核验，将信息保存
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(avatar);
        userInfoApi.update(userInfo);
    }

    public UserInfoVo findByid(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if(userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
